import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_homemonitor/util/CommonConstant.dart';
import 'dart:async';
// import 'index_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_homemonitor/util/toast.dart';

import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
// import 'Select.dart';
// import 'Unique.dart';
import 'package:flutter_homemonitor/util/NetLoadingDialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'HomePage.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => new _LoginState();
}

class _LoginState extends State<Login> {
  String _platformVersion = '未知版本';
  String downLoadUrl = "http://120.25.160.53/shxs_files/Apk版本文件/";
//  Permission permission;
  String version = "当前版本 : ";
  TextEditingController _PasswordController = TextEditingController();
  TextEditingController _UsernameController = TextEditingController();

  TextEditingController _PasswordController2 = TextEditingController();
  TextEditingController _UsernameController2 = TextEditingController();
  String? Unique = '';
  String VersionInfo = "";
  String UpdateApkPath = "";
  String UpdateApkVersion = "";
  String UpdateApkContent = "";
  bool loading = false;

  String UpdateDate = ""; //每日只跳一次更新

  // 响应空白处的焦点的Node
  FocusNode blankNode = FocusNode();

  static const channelName = 'plugins.iwubida.com/update_version';
  static const stream = const EventChannel(channelName);
  // 进度订阅
  StreamSubscription? downloadSubscription;
  int percent = 0;

  String iosurl = "http://itunes.apple.com/cn/app/id1461727775";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    print(1111111111);
    _ReadLoginInfo();
//    print(222222222222);
    initPlatformState();
//    print(33333333333333);
    downLoad();
  }

  @override
  Widget build(BuildContext context) {
    //Navigator.push(context, MaterialPageRoute(builder: (context)=>new SecondScreen()));
    return Container(
        child: Scaffold(
//            appBar: PreferredSize(child:AppBar(
//              title: Text('设 备 运 行 管 理',style: TextStyle( fontFamily: "BenMoYouYuan")),
//              centerTitle: true,
//            ),
//              preferredSize: Size.fromHeight(50)//外嵌PreferredSize ,设置appbar高度
//          ),
//        resizeToAvoidBottomPadding: false,//输入框输入法弹出不形变
            body: GestureDetector(
                onTap: () {
                  // 点击空白页面关闭键盘
                  FocusScope.of(context).requestFocus(blankNode);
                },
                child: Container(
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                            child: Container(
                                child: new ListView(children: <Widget>[
                          //用户名
                          Container(
                            child: new Column(children: <Widget>[
                              new Container(
                                child: Center(
                                  child: new Text('房屋检测',
                                      style: TextStyle(
                                          fontSize: 45.0,
                                          fontWeight: FontWeight.bold,
                                          color: Color.fromARGB(
                                              255, 255, 255, 255),
                                          fontFamily: "BenMoYouYuan")),
                                ),
                              ),
                              // new Container(
                              //   child: Center(
                              //     child: new Text('设备运行管理',
                              //         style: TextStyle(
                              //             fontSize: 30.0,
                              //             fontWeight: FontWeight.bold,
                              //             color: Color.fromARGB(
                              //                 255, 255, 255, 255),
                              //             fontFamily: "BenMoYouYuan")),
                              //   ),
                              // ),
                            ]),
                            margin: EdgeInsets.fromLTRB(20.0, 60.0, 20.0, 0),
                          ),

                          //用户名1
                          Container(
                            child: new Row(children: <Widget>[
                              new Container(
                                child: Expanded(
                                    child: Theme(
                                  data: new ThemeData(
                                      primaryColor: Colors.white,
                                      hintColor: Colors.white),
                                  child: TextField(
                                    controller: _UsernameController,
                                    decoration: InputDecoration(
                                      border: OutlineInputBorder(),
                                      fillColor: Colors.transparent,
                                      labelText: '用户名1',
                                      labelStyle: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontFamily: "BenMoYouYuan"),
                                    ),
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white),
                                    autofocus: false,
                                  ),
                                )),
                              )
                            ]),
                            margin: EdgeInsets.fromLTRB(30.0, 60.0, 30.0, 0),
                          ),
                          //密码
                          Container(
                            child: new Row(children: <Widget>[
                              new Container(
                                child: Expanded(
                                  child: Theme(
                                    data: new ThemeData(
                                        primaryColor: Colors.white,
                                        hintColor: Colors.white),
                                    child: TextField(
                                      controller: _PasswordController,
                                      decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.white,
                                                width: 10.0)),
                                        fillColor: Colors.white,
                                        labelText: '密  码1',
                                        labelStyle: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: Color.fromARGB(
                                                255, 255, 255, 255),
                                            fontFamily: "BenMoYouYuan"),
                                      ),
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Color.fromARGB(
                                              255, 255, 255, 255)),
                                      autofocus: false,

                                      //输入密码，需要用*****显示
                                      obscureText: true,
                                    ),
                                  ),
//                           color: Color.fromARGB(255, 255, 255, 255),
                                ),
                              )
                            ]),
                            margin: EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 0),
                          ),
                          //用户名2
                          Container(
                            child: new Row(children: <Widget>[
                              new Container(
                                child: Expanded(
                                    child: Theme(
                                  data: new ThemeData(
                                      primaryColor: Colors.white,
                                      hintColor: Colors.white),
                                  child: TextField(
                                    controller: _UsernameController2,
                                    decoration: InputDecoration(
                                      border: OutlineInputBorder(),
                                      fillColor: Colors.transparent,
                                      labelText: '用户名2',
                                      labelStyle: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontFamily: "BenMoYouYuan"),
                                    ),
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white),
                                    autofocus: false,
                                  ),
                                )),
                              )
                            ]),
                            margin: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 0),
                          ),
                          //密码
                          Container(
                            child: new Row(children: <Widget>[
                              new Container(
                                child: Expanded(
                                  child: Theme(
                                    data: new ThemeData(
                                        primaryColor: Colors.white,
                                        hintColor: Colors.white),
                                    child: TextField(
                                      controller: _PasswordController2,
                                      decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.white,
                                                width: 10.0)),
                                        fillColor: Colors.transparent,
                                        labelText: '密  码2',
                                        labelStyle: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: Color.fromARGB(
                                                255, 255, 255, 255),
                                            fontFamily: "BenMoYouYuan"),
                                      ),
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Color.fromARGB(
                                              255, 255, 255, 255)),
                                      autofocus: false,

                                      //输入密码，需要用*****显示
                                      obscureText: true,
                                    ),
                                  ),
//                           color: Color.fromARGB(255, 255, 255, 255),
                                ),
                              )
                            ]),
                            margin: EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 0),
                          ),
                          Container(
                            child: new Row(
                              children: <Widget>[
                                Expanded(
                                    child: Container(
                                  child: ElevatedButton(
                                    onPressed: _Login,
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: Color.fromARGB(
                                          255, 103, 117, 149), // 背景色
                                    ),
                                    child: new Text('登录',
                                        style: TextStyle(
                                            fontSize: 20.0,
                                            color: Color.fromARGB(
                                                255, 255, 255, 255),
                                            fontFamily: "BenMoYouYuan")),
                                  ),
                                  height: 75.0,
                                  padding: new EdgeInsets.fromLTRB(
                                      10.0, 10.0, 10.0, 10.0),
                                )),
                              ],
                            ),
                            margin: EdgeInsets.fromLTRB(30.0, 60.0, 30.0, 0),
                          ),
                        ]))),
                        Container(
                          child: Text(version,
                              style: TextStyle(
                                  color: Colors.black,
                                  fontFamily: "BenMoYouYuan")),
                          margin: EdgeInsets.fromLTRB(0, 0, 0, 1.0),
                          alignment: Alignment(0, 1),
                        ),
                      ]),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("images/bg.jpg"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ))));
  }

  Future _Login() async {
    Navigator.pushAndRemoveUntil(context,
        new MaterialPageRoute(builder: (BuildContext context) {
      return MyHomePage();
    }), (route) => route == Null);
//     if (_UsernameController.text.toString().isEmpty ||
//         _UsernameController2.text.toString().isEmpty) {
//       Toast.toast(context, "用户名不能为空", 4, 5);
//
//       return;
//     }
//     if (_PasswordController.text.toString().isEmpty ||
//         _PasswordController2.text.toString().isEmpty) {
//       Toast.toast(context, "密码不能为空", 4, 5);
//       return;
//     }
//     DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
//     if (Platform.isIOS) {
//       //ios相关代码
//       IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
//       print('Running on ${iosInfo.utsname.machine}');
//       Unique = iosInfo.identifierForVendor;
//     } else if (Platform.isAndroid) {
//       //android相关代码
// //      uuid=
//
//       AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
//       Unique = androidInfo.id;
// //      androidInfo.id
//       print('Running on ${androidInfo.id}');
//     }
//
//     print(11111111111);
//     showDialog(
//         context: context,
//         barrierDismissible: false,
//         builder: (dialog) {
//           return NetLoadingDialog(
//             loadingText: '登录中...',
//             requestCallBack: _register(dialog),
//             outsideDismiss: false,
//           );
//         });
  }

  Future postHttp(String Username, String Password, String UserCode) async {
    try {
      Response response;
      print(Username + "," + Password + "," + UserCode);
      var data = {
        'UserCode': Username,
        'UserPassWord': Password,
        'IMEI': UserCode
      };
      response = await Dio().post(CommonConstant.Login, data: data);

      return response.data;
    } on DioError catch (error) {
      // 超时
      if (error.type == DioExceptionType.connectionTimeout) {
        Toast.toast(context, "网络超时，请重试", 4, 5);

        return null;
      }
    } catch (e) {
      print('11111111111');
      print(e.toString());
      return null;
    }
  }

  Future _SaveUsername(var val) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString('username', _UsernameController.text.toString());
    preferences.setString('password', _PasswordController.text.toString());
    preferences.setString('usernameid', val['data']['Id'].toString());
    preferences.setString('PhoneNumber', val['data']['TEL'].toString());
    print('存储acount为:' + _UsernameController.text.toString());
    var roleslist = val['data']['RoleName'] as List;
    String company = val['data']['company']['name'].toString();
    bool HasCreatAuthority = false;
    bool fangjiancompany = false;
    bool jiancecompany = false;
    if (company.contains('房屋检测公司')) {
      fangjiancompany = true;
      roleslist.forEach((roles) {
        if (roles.toString() == '超级管理员' ||
            roles.toString() == '部门管理员' ||
            roles.toString() == '项目负责人') {
          HasCreatAuthority = true;
        }
      });
    } else if (company.contains('检测公司')) {
      jiancecompany = true;
    }
    preferences.setBool('HasCreatAuthority', HasCreatAuthority);
    preferences.setBool('fangjiancompany', fangjiancompany);
    preferences.setBool('jiancecompany', jiancecompany);
//    print("权限："+roleslist);
//    print("权限："+(roleslist.length).toString());
  }

  Future _ReadLoginInfo() async {
    String username = "";
    String password = "";
    SharedPreferences preferences = await SharedPreferences.getInstance();
    username = preferences.getString('username') ?? '';
    password = preferences.getString('password') ?? '';

//    print('读取到acount为:$account');
    print(username);
    if (username != null) {
      setState(() {
        //    _UsePersonController=account;
        _UsernameController =
            TextEditingController.fromValue(TextEditingValue(text: username));
        _PasswordController =
            TextEditingController.fromValue(TextEditingValue(text: password));
      });
    }
  }

  Future initPlatformState() async {
    String? versionInfo = '';
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      versionInfo = packageInfo.version;
    } catch (e) {
      print("获取版本失败");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      version += versionInfo ?? '';
      VersionInfo = versionInfo ?? '';
      print("version：" + version);
      print("版本：" + version);
//     checkPermission();
//      requestPermission()
    });
  }

//  //是否有权限
//  Future<bool> checkPermission() async {
//    bool res = await SimplePermissions.checkPermission(
//        Permission.WriteExternalStorage);
////    print(res);
//    return res;
//  }
//
//  //打开权限
//  Future<PermissionStatus> requestPermission() async {
//    return SimplePermissions.requestPermission(Permission.WriteExternalStorage);
//  }

  Future downLoad() async {
    await new Future.delayed(new Duration(milliseconds: 2000));
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    ;
    SharedPreferences preferences = await SharedPreferences.getInstance();
    UpdateDate = preferences.getString("UpdateDate") ?? '';
    print(DateTime.now().year.toString() +
        "-" +
        DateTime.now().month.toString() +
        "-" +
        DateTime.now().day.toString());
    //每日只跳一次更新
    if (UpdateDate ==
        DateTime.now().year.toString() +
            "-" +
            DateTime.now().month.toString() +
            "-" +
            DateTime.now().day.toString()) {
      return;
    } else {
      preferences.setString(
          'UpdateDate',
          DateTime.now().year.toString() +
              "-" +
              DateTime.now().month.toString() +
              "-" +
              DateTime.now().day.toString());
    }

    GetApkVerson().then((val) {
      print(111111111111);
      if (val != null) {
        print(2222222222222222);
        if (val['Version'].toString() != VersionInfo) {
          //弹出窗口
          setState(() {
            UpdateApkVersion = val['Version'].toString();
            UpdateApkPath = val['Path'].toString();
            UpdateApkContent = val['Content'].toString();
          });

          if (Platform.isIOS) {
            //IOS不做处理

            showlog(iosurl);
          } else if (Platform.isAndroid) {
//            AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
//            print(androidInfo.version.release);
//      new AppUpdater(getContext(),url).start();
            showlog(UpdateApkPath);
//            print(0000000000);
//            ShowDialog();  //更新显示dialog
          }
        }
      }
    });
  }

  Future GetApkVerson() async {
    try {
      Response response;
      response = await Dio().get(CommonConstant.Verson);
      print(response.data);
      return response.data;
    } catch (e) {
      print("-1-1-1-1-1-1-1-1-1");
      print("异常：" + e.toString());
      return null;
    }
  }

  _register(BuildContext dialog) {
    postHttp(_UsernameController.text.toString(),
            _PasswordController.text.toString(), Unique ?? '')
        .then((val) {
      Navigator.pop(dialog); //关闭对话框
      if (val == null) {
        return;
      }
//      print(val);

      if (val['message'].toString() == '登录成功') {
        _SaveUsername(val);

//      //跳转并销毁当前
//         Navigator.pushAndRemoveUntil(context,
//             new MaterialPageRoute(builder: (BuildContext context) {
//           return SelectPage();
//         }), (route) => route == Null);

        print("登录成功");
      } else {
        if (val['message'].toString() == "手机认证码不正确") {
          Toast.toast(context, "手机认证失败", 4, 5);
          // Navigator.push(context, new MaterialPageRoute(builder: (context) => new unique()));
        } else {
          Toast.toast(context, val['message'].toString(), 4, 5);
        }
      }
    });
  }

// 获取安装地址
//  Future<String> get _apkLocalPath async {
//    final directory = await getExternalStorageDirectory();
//    return directory.path;
//  }

// 下载
//
//    void executeDownload() async {
////      Response response;
////      try {
////
////        final path = await _apkLocalPath;
////         print(path);
////        response = await Dio().download("http://120.25.160.53/shxs_files/Apk版本文件/Hermes2App_5.0.3.apk", "./Hermes2App_5.0.3.apk",onReceiveProgress: (int count, int total){
////          //进度
////          print("$count $total");
////        });
////        print('downloadFile success---------${response.data}');
////      } on DioError catch (e) {
////        print('downloadFile error---------$e');
////        print(e);
////      }
////      return response.data;
//      tryOtaUpdate();
//    }

//  // 下载
//  Future<void> tryOtaUpdate() async {
//  try {
//  //LINK CONTAINS APK OF FLUTTER HELLO WORLD FROM FLUTTER SDK EXAMPLES
//  OtaUpdate().execute('http://120.25.160.53/shxs_files/Apk版本文件/Hermes2App_5.0.3.apk').listen(
//  (OtaEvent event) {
//  print('OTA status: ${event.status} : ${event.value} ');
//  setState(() {
//    currentProgress=int.parse(event.value);
//  });
//  },
//  );
//  } catch (e) {
//  print('Failed to make OTA update. Details: $e');
//  }
//  }

//    print("1111");
//  final path = await _apkLocalPath;
//    print(path.toString());
//    print("2222");
//
//    final taskId = await FlutterDownloader.enqueue(
////  url: downLoadUrl + '/app-release.apk',
//  url: UpdateApkPath,
//  savedDir: path,
//  showNotification: true,
//  openFileFromNotification: true);
//    print("33333");
//    FlutterDownloader.registerCallback((id, status, progress) {
//      // 当下载完成时，调用安装
//      if (taskId == id && status == DownloadTaskStatus.complete) {
//        _installApk();
//      }
//    });

//// 安装
//  Future<Null> _installApk() async {
//    print("安装111");
//  // XXXXX为项目名
//  const platform = const MethodChannel("com.skygeoinfo.ui");
//    print("安装2222");
//  try {
//  final path = await _apkLocalPath;
//  print("安装33333");
//  // 调用APP地址
////  await platform.invokeMethod('install', {'path': path + '/app-release.apk'});
//    print(path);
//    print(path + '/Hermes2App_5.0.3.apk');
//  await platform.invokeMethod('install', {'path': path + '/Hermes2App_5.0.3.apk'});
//    print("安装4444444444");
//  } on PlatformException catch (_) {
//    print("安装555555555555");
//  }
//  }

//
//  void ShowDialog() {
//    showDialog(
//      // 传入 context
//      context: context,
//
//      // 构建 Dialog 的视图
//      builder: (update) => Padding(
//        padding: EdgeInsets.all(16),
//
//          child: Column(
//          mainAxisAlignment: MainAxisAlignment.center,
//          crossAxisAlignment: CrossAxisAlignment.stretch,
//          children: <Widget>[
//            Container(
//
//              alignment: Alignment.center,
//              color: Colors.white,
//              child: Column(
//                children: <Widget>[
//
//                   Container(
//                    child: Text('发现新版本',style: TextStyle(
//                        fontSize: 20,color: Colors.black38,decoration: TextDecoration.none, fontFamily: "BenMoYouYuan")
//
//                   )
//                  )
//                ],
//              ),
//              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
//            ) , Container(
//              alignment: Alignment.centerLeft,
//              color: Colors.white,
//              child: Row(
//                children: <Widget>[
//
//
//                  new Center(
//                    child: Text('更新版本:'+UpdateApkVersion,
//                        style: TextStyle(
//                            fontSize: 16,
//                            color: Colors.black38,decoration: TextDecoration.none, fontFamily: "BenMoYouYuan")),
//                  )
//                ],
//              ),
//              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
//            )
//            , Container(
//              alignment: Alignment.centerLeft,
//              color: Colors.white,
//              child: Row(
//                children: <Widget>[
//
//
//                  new Center(
//                        child: Text('更新内容:'+UpdateApkContent,
//                            style: TextStyle(
//                                fontSize: 16,color: Colors.black38,decoration: TextDecoration.none, fontFamily: "BenMoYouYuan")),
//                      )
//                ],
//              ),
//              padding: EdgeInsets.fromLTRB(0, 10, 0, 20),
//            ),
//
////            //更新线
////            Container(
////              alignment: Alignment.centerLeft,
////              color: Colors.white,
////              child: Column(
////                children: <Widget>[
////                ],
////              ),
////              padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
////            ),
//            Container(
//              alignment: Alignment.center,
//              color: Colors.white,
//              child: Column(
//                children: <Widget>[
//                  new Center(
//                      child:
//                      Padding(
//                        padding: EdgeInsets.only(top: 1, bottom: 1),
//                        child: FlatButton(
//                            onPressed: () {
//                              // 关闭 Dialog
//                               print("点击更新按钮");
////                              tryOtaUpdate();
//                              print("新版本222222222222222");
//
////                              _launchURL();
////                        Navigator.pushAndRemoveUntil(context,
////                      new MaterialPageRoute(builder: (BuildContext context) {return BezierCurve();}), (route) => route == Null);
//
//                                 },
//                            child: Text('更新',style: TextStyle(color: Colors.black38, fontFamily: "BenMoYouYuan"),)),
//                      )),
//                      new Center(
//                      child:
//                      Padding(
//                      padding: EdgeInsets.only(top: 1, bottom: 1),
//                      child: FlatButton(
//                      onPressed: () {
//                      // 关闭 Dialog
//                      Navigator.pop(update);
//                      },
//                      child: Text('取消',style: TextStyle(color: Colors.black38, fontFamily: "BenMoYouYuan"))),
//
//                      ))
//                ],
//              ),
//            )
//          ],
//
//        ),
//
//
//      ),
//
//    );
//
//  }

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  void showlog(String url) {
    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
//            title: new Text("提 示"),
                content: new Text("发现新版本，是否更新",
                    style: TextStyle(
                        fontSize: 20.0,
                        color: Colors.blueAccent,
                        fontFamily: "BenMoYouYuan")),
                actions: <Widget>[
                  new TextButton(
                    child: new Text("下载更新",
                        style: TextStyle(
                            fontSize: 16.0,
                            color: Colors.blueAccent,
                            fontFamily: "BenMoYouYuan")),
                    onPressed: () {
                      _launchURL(url);
                    },
                  ),
                  new TextButton(
                    child: new Text("取消",
                        style: TextStyle(
                            fontSize: 16.0,
                            color: Colors.blueAccent,
                            fontFamily: "BenMoYouYuan")),
                    onPressed: () {
                      Navigator.of(context).pop(_);
                    },
                  )
                ]));
  }
}
